package com.anos.smsfun.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.anos.smsfun.R;
import com.anos.smsfun.adapter.SelectContactAdapter;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.controller.DataRequestCallback;
import com.anos.smsfun.customview.IndexableListView;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.task.DoingBackground;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.Utils;

public class SelectContactActivity extends Activity implements
		OnQueryTextListener, OnItemClickListener, OnClickListener,
		OnCloseListener {

	private IndexableListView listViewContact;
	private Button btnSelect;
	private Button btnCancel;

	private SelectContactAdapter mContactsAdapter;
	private ArrayList<ContactsWrapper> mContactsWrappers = new ArrayList<ContactsWrapper>();
	private ArrayList<ContactsWrapper> mContactsSelected = new ArrayList<ContactsWrapper>();
	private SearchView mSearchView;

	private SMSFunDataCache mSmsFunDataCache;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_contact);

		Utils.setUpActionBar(this);
		/**
		 * set title view
		 */
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflator.inflate(R.layout.title_view, null);
		((TextView) v.findViewById(R.id.tvTitle_ab))
				.setText(getString(R.string.title_select_contact));
		((TextView) v.findViewById(R.id.tvNumber_ab))
				.setText(getString(R.string.title_hint_new_msg));
		getActionBar().setCustomView(v);

		// find view id
		findViewByIdAll();

		// init data cache
		mSmsFunDataCache = SMSFunDataCache.getInstance(this);

		if (mContactsWrappers.size() == 0)
			mContactsWrappers = mSmsFunDataCache.getContactList();

		if (mContactsWrappers != null && mContactsWrappers.size() > 0) {
			mContactsAdapter = new SelectContactAdapter(this, mContactsWrappers);
			listViewContact.setAdapter(mContactsAdapter);
		} else {
			getContactList();
		}
	}

	private void findViewByIdAll() {
		listViewContact = (IndexableListView) findViewById(R.id.listview_select);
		btnSelect = (Button) findViewById(R.id.btnSelect_select);
		btnCancel = (Button) findViewById(R.id.btnCancel_select);

		listViewContact.setFastScrollEnabled(true);
		listViewContact.setOnItemClickListener(this);
		btnSelect.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	/**
	 * custom search view
	 */
	private void customSearchView() {
		int id = mSearchView.getContext().getResources()
				.getIdentifier("android:id/search_src_text", null, null);
		int searchButtonId = getResources().getIdentifier(
				"android:id/search_button", null, null);
		int closeButtonId = getResources().getIdentifier(
				"android:id/search_close_btn", null, null);

		TextView textView = (TextView) mSearchView.findViewById(id);
		textView.setTextColor(Color.WHITE);
		textView.setHintTextColor(Color.WHITE);

		ImageView searchIconImg = (ImageView) mSearchView
				.findViewById(searchButtonId);
		searchIconImg.setImageResource(R.drawable.ic_search);

		ImageView closeIconImg = (ImageView) mSearchView
				.findViewById(closeButtonId);
		closeIconImg.setImageResource(R.drawable.ic_search_close);
	}

	/**
	 * get list contact
	 */
	private void getContactList() {
		mContactsWrappers.clear();
		DoingBackground.getContactList(this, mContactListCallback);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mContactsWrappers.clear();
	}

	private DataRequestCallback<ArrayList<ContactsWrapper>> mContactListCallback = new DataRequestCallback<ArrayList<ContactsWrapper>>() {

		@Override
		public void onResult(ArrayList<ContactsWrapper> result,
				boolean continueWaiting) {
			Context c = SelectContactActivity.this;

			if (result != null && !result.isEmpty()) {
				mContactsWrappers.addAll(result);

				mContactsAdapter = new SelectContactAdapter(c,
						mContactsWrappers);
				listViewContact.setAdapter(mContactsAdapter);
				mContactsAdapter.notifyDataSetChanged();

				// save database
				mSmsFunDataCache.saveContactsList(mContactsWrappers);
			} else {
				if (!continueWaiting) {
					// Có lỗi xảy ra khi request dữ liệu
					Toast.makeText(c, R.string.loading_error_toast,
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_search_contact, menu);
		MenuItem searchItem = menu.findItem(R.id.action_search);
		mSearchView = (SearchView) searchItem.getActionView();
		// custom searchview
		customSearchView();
		mSearchView.setOnQueryTextListener(this);
		mSearchView.setOnCloseListener(this);
		return super.onCreateOptionsMenu(menu);
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
//                if (mContactsSelected.size() > 0) {
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelableArrayList(
//                            DefConstants.PUT_LIST_SELECT_CONTACT, mContactsSelected);
//                    Intent intent = getIntent();
//                    intent.putExtras(bundle);
//                    setResult(DefConstants.REQ_CODE_SELECT_CONTACT, intent);
                    finish();
//                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
	public boolean onQueryTextChange(String newText) {
		try {
			final ArrayList<ContactsWrapper> lstSearchResult = new ArrayList<ContactsWrapper>();
			for (int i = 0; i < mContactsWrappers.size(); i++) {
				// search display name
				String strDisplayName = mContactsWrappers.get(i)
						.getDisplayName().trim().toUpperCase();
				String strPhoneNumber = mContactsWrappers.get(i)
						.getDisplayNumber().trim();
				newText = newText.replace("0", "+84");
				if (newText.length() <= strDisplayName.length()
						|| newText.length() <= strPhoneNumber.length()) {
					if (strDisplayName.indexOf(newText.trim().toUpperCase()) != -1
							|| strPhoneNumber.indexOf(newText) != -1) {
						lstSearchResult.add(mContactsWrappers.get(i));
					}
				}
			}
			// refresh list
			mContactsAdapter = new SelectContactAdapter(
					SelectContactActivity.this, lstSearchResult);
			listViewContact.setAdapter(mContactsAdapter);
			mContactsAdapter.notifyDataSetChanged();
			// on item click
			listViewContact.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> av, View v,
						int position, long id) {
					// SelectItemHolder viewHolder = (SelectItemHolder)
					// v.getTag();
					ContactsWrapper contact = lstSearchResult.get(position);
					if (contact != null) {
						if (!mContactsSelected.contains(contact)) {
							mContactsSelected.add(contact);
							// viewHolder.chkBox.setChecked(true);
							contact.setIsUse(true);
							mContactsAdapter.notifyDataSetChanged();
						} else {
							mContactsSelected.remove(contact);
							// viewHolder.chkBox.setChecked(false);
							contact.setIsUse(false);
							mContactsAdapter.notifyDataSetChanged();
						}
					}
					btnSelect.setText(getString(R.string.text_selected) + " ("
							+ mContactsSelected.size() + ")");
				}
			});

		} catch (Exception e) {
			return false;
		}
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
		// SelectItemHolder viewHolder = (SelectItemHolder) v.getTag();
		ContactsWrapper contact = mContactsWrappers.get(position);
		if (contact != null) {
			if (!mContactsSelected.contains(contact)) {
				mContactsSelected.add(contact);
				// viewHolder.chkBox.setChecked(true);
				contact.setIsUse(true);
				mContactsAdapter.notifyDataSetChanged();
			} else {
				mContactsSelected.remove(contact);
				// viewHolder.chkBox.setChecked(false);
				contact.setIsUse(false);
				mContactsAdapter.notifyDataSetChanged();
			}
		}
		btnSelect.setText(getString(R.string.text_selected) + " ("
				+ mContactsSelected.size() + ")");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSelect_select:
			if (mContactsSelected.size() > 0) {
				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList(
						DefConstants.PUT_LIST_SELECT_CONTACT, mContactsSelected);
				Intent intent = getIntent();
				intent.putExtras(bundle);
				setResult(DefConstants.REQ_CODE_SELECT_CONTACT, intent);
				finish();
			}
			break;

		case R.id.btnCancel_select:
			mContactsSelected.clear();
			btnSelect.setText(getString(R.string.text_selected) + " ("
					+ mContactsSelected.size() + ")");
			for (ContactsWrapper contact : mContactsWrappers) {
				contact.setIsUse(false);
			}
			mContactsAdapter.notifyDataSetChanged();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onClose() {
		return false;
	}
}
